<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { IconPicker } from '@/components/IconPicker'
import { ElPopover } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, onMounted } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { getMenuListApi } from '@/api/backstage'
// import { ElButton, ElInput, ElPopconfirm, ElTable, ElTableColumn, ElTag } from 'element-plus'
// import { AddButtonPermission } from './index'
// import { BaseButton } from '@/components/Button'
import { cloneDeep } from 'lodash-es'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  },
  searchParams: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const handleClose = async (tag: any) => {
  const formData = await getFormData()
  // 删除对应的权限
  setValues({
    permissionList: formData?.permissionList?.filter((v: any) => v.value !== tag.value)
  })
}

const handleEdit = async (row: any) => {
  // 深拷贝当前行数据到编辑行
  permissionEditingRow.value = { ...row }
}

const handleSave = async () => {
  const formData = await getFormData()
  const index = formData?.permissionList?.findIndex((x) => x.id === permissionEditingRow.value.id)
  if (index !== -1) {
    formData.permissionList[index] = { ...permissionEditingRow.value }
    permissionEditingRow.value = null // 重置编辑状态
  }
}

const showDrawer = ref(false)
// 存储正在编辑的行的数据
const permissionEditingRow = ref<any>(null)

const formSchema = reactive<FormSchema[]>([
  {
    field: 'type',
    label: '菜单类型',
    component: 'RadioButton',
    value: 0,
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '目录',
          value: 0
        },
        {
          label: '菜单',
          value: 1
        },
        {
          label: '按钮链接',
          value: 2
        }
      ],
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val === 1) {
            setSchema([
              {
                field: 'routePath',
                path: 'componentProps.disabled',
                value: false
              }
            ])
            setValues({
              component: unref(cacheComponent)
            })
          } else {
            setSchema([
              {
                field: 'routePath',
                path: 'componentProps.disabled',
                value: true
              }
            ])

            // TODO:暂不做处理
            // if (formData.parentId === void 0) {
            //   setValues({
            //     component: '#'
            //   })
            // } else {
            //   setValues({
            //     component: '##'
            //   })
            // }
          }
        }
      }
    }
  },
  {
    field: 'parentId',
    label: '父级菜单',
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'id',
      props: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true,
      on: {
        change: async (val: number) => {
          console.log(val)
          const formData = await getFormData()
          // TODO:等待逻辑确认
          // if (val && formData.type === 0) {
          //   setValues({
          //     component: '##'
          //   })
          // } else if (!val && formData.type === 0) {
          //   setValues({
          //     component: '#'
          //   })
          // } else
          if (formData.type === 1) {
            setValues({
              component: unref(cacheComponent) ?? ''
            })
          }
        }
      }
    },
    optionApi: async () => {
      const res = await getMenuListApi(props.searchParams || {})
      return res.data || []
    }
  },
  {
    field: 'name',
    label: '资源名称',
    component: 'Input'
  },
  {
    field: 'routePath',
    label: '组件路径',
    component: 'Input',
    value: '',
    componentProps: {
      disabled: true,
      placeholder: '请输入',
      on: {
        change: (val: string) => {
          cacheComponent.value = val
        }
      }
    }
  },
  {
    field: 'alias',
    label: '资源别名',
    component: 'Input'
  },
  {
    field: 'routeWay',
    label: '路由地址',
    component: 'Input'
  },
  {
    field: 'menuPosition',
    label: '菜单位置',
    value: 0,
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '左侧菜单',
          value: 0
        },
        {
          label: '顶部菜单',
          value: 1
        },
        {
          label: '其他位置',
          value: 3
        }
      ]
    }
  },
  {
    field: 'icon',
    label: '资源图标', // 应该做成下拉选择的图标选择器，此处仅为示意
    component: 'IconPicker',
    componentProps: {
      placeholder: '点击选择图标'
    }
  },
  {
    field: 'status',
    label: '状态',
    value: 0,
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '正常',
          value: 0
        },
        {
          label: '停用',
          value: 1
        }
      ]
    }
  },
  {
    field: 'show',
    label: '是否显示',
    value: 0,
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '显示',
          value: 0
        },
        {
          label: '隐藏',
          value: 1
        }
      ]
    }
  },
  {
    field: 'sortOrder',
    label: '显示排序',
    value: 1,
    component: 'InputNumber',
    componentProps: {
      min: 0
    }
  },
  {
    field: 'outside',
    label: '是否外链',
    value: 0,
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '否',
          value: 0
        },
        {
          label: '是',
          value: 1
        }
      ]
    }
  },
  {
    field: 'proxy',
    label: '是否代理',
    value: 0,
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '无',
          value: 0
        },
        {
          label: '重定向',
          value: 1
        },
        {
          label: '代理',
          value: 2
        }
      ]
    }
  },
  {
    field: 'redirectShow',
    label: '重定向显示',
    component: 'Input'
  },
  {
    field: 'redirect',
    label: '重定向',
    component: 'Input'
  },
  {
    field: 'routes',
    label: '路由参数',
    component: 'Input'
  },
  {
    field: 'args',
    label: '参数转换',
    component: 'Input'
  },
  {
    field: 'originRouteWay',
    label: '原路由地址',
    component: 'Input'
  },
  {
    field: 'originRoutePath',
    label: '原组件地址',
    component: 'Input'
  }
])

const rules = reactive({
  name: [required()],
  menuPosition: [required()],
  type: [required()],
  status: [required()],
  show: [required()],
  outside: [required()],
  proxy: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, getComponentExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

const cacheComponent = ref('')

watch(
  () => props.currentRow,
  (value) => {
    if (!value) return
    const currentRow = cloneDeep(value)
    // console.log('currentRow', currentRow)

    cacheComponent.value = currentRow.type === 1 ? currentRow.routePath : ''
    if (currentRow.parentId === 0) {
      setSchema([
        {
          field: 'routePath',
          path: 'componentProps.disabled',
          value: true
        }
      ])
    } else {
      setSchema([
        {
          field: 'routePath',
          path: 'componentProps.disabled',
          value: false
        }
      ])
    }
    if (currentRow.type === 1) {
      setSchema([
        {
          field: 'routePath',
          path: 'componentProps.disabled',
          value: false
        }
      ])
    } else {
      setSchema([
        {
          field: 'routePath',
          path: 'componentProps.disabled',
          value: true
        }
      ])
    }
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
onMounted(() => {
  // console.profileEnd('action')
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
